/**
 * File: MaqBfqProcessor.java
 * Created by: mhaimel
 * Created on: 7 Jul 2009
 * CVS:  $Id: MaqBfqProcessor.java,v 1.2 2009/10/09 15:12:39 mhaimel Exp $
 */
package uk.ac.ebi.curtain.processor.maq.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import uk.ac.ebi.curtain.controller.maq.MaqBean;
import uk.ac.ebi.curtain.controller.maq.MaqBfqOutputBean;
import uk.ac.ebi.curtain.processor.AbstractProcessor;
import uk.ac.ebi.curtain.util.ExecutionService;
import uk.ac.ebi.curtain.utils.file.FileInfo;

import com.google.inject.Inject;

/**
 * @author mhaimel
 *
 */
public class MaqBfqProcessor extends  AbstractProcessor<MaqBean, MaqBfqOutputBean> {
	private static final String FASTQ2BFQ_OPT = "fastq2bfq";
	private Log log = LogFactory.getLog(this.getClass());
	private ExecutionService executionService;
	private MaqBfqOutputBean outBean = null;

	@Override
	protected MaqBfqOutputBean buildReturnObject() {
		return outBean;
	}

	@Override
	public void process() {
		outBean = new MaqBfqOutputBean();
		File baseDir = getInput().getReadDir();
		outBean.setBaseDir(baseDir);
		List<File> bfqPair = transform2Bfq(baseDir, getInput().getReadBfqList());
		outBean.getBfqPairList().addAll(bfqPair);
		outBean.setReadFiles(getInput().getReadFiles());
	}
	
	
	public List<File> transform2Bfq(File baseDir, List<FileInfo> fileList) {
		getLog().debug("Transform Fastq 2 bfq: " + fileList.size());
		List<File> list = new ArrayList<File>();
		for(FileInfo fi : fileList){
			if(isForceShutdown()){
				getLog().warn("FORCE shutdown!");
				break;
			}
			list.add(transform2Bfq(baseDir,fi));
		}
		return list;
	}
	
	private File transform2Bfq(File baseDir, FileInfo file) {
		getLog().debug("Transform file 2 bfq " + file);
		File bfq = new File(baseDir,file.getNameWithoutFilePostfix()+".bfq");
		List<String> cmds = new ArrayList<String>();
		cmds.add(getConfig().getMaqExec());
		cmds.add(FASTQ2BFQ_OPT);
		cmds.add(file.getFile().getAbsolutePath());
		cmds.add(bfq.getAbsolutePath());
		File logF = getNextFile(baseDir, bfq.getName()+"_", ".log");
		File errF = getNextFile(baseDir, bfq.getName()+"_", ".err");if(isForceShutdown()){
			getLog().warn("FORCE shutdown - not processed: " + bfq);
			return bfq;
		}
		getExecutionService().exec(baseDir, cmds.toArray(new String[0]), logF, errF,false,true);
		return bfq;
	}
	
	
	private File getNextFile(File dir, String prefix, String postfix) {
		return getExecutionService().getNextFile(dir, prefix, postfix);
	}
	
	@Inject
	public void setExecutionService(ExecutionService executionService) {
		this.executionService = executionService;
	}

	protected ExecutionService getExecutionService() {
		return executionService;
	}
	
}
